# coding: latin-1
from __future__ import with_statement
from Tkinter import *
from WindowView import *
from CourseModel import *


class MainWindow(Tk):

    def to_previous_page(self):
        self.table.previous_page()

    def to_next_page(self):
        self.table.next_page()

    def __init__(self, source):
        Tk.__init__(self)
        self.source = source
        self.create_menus()
        self.title("Kursseja")
        controls = Frame(self)
        b = Button( controls,
                    text="Edellinen sivu",
                    command=self.to_previous_page )
        b.pack(side=LEFT)
        b = Button( controls,
                    text="Seuraava sivu",
                    command=self.to_next_page )
        b.pack(side=LEFT)
        controls.pack(side=TOP, fill=X)

        self.table = WindowView(self, source)
        self.table.pack( side=TOP, expand=1, fill=BOTH )

    def export(self, filename):
        with open(filename, "w") as f:
            for col in range(self.source.columns()):
                f.write(self.source.header(col) + "\t")
            f.write("\n")
            for row in range(self.source.rows()):
                for col in range(self.source.columns()):
                    f.write(self.source.get(row, col) + "\t")
                f.write("\n")

    def create_menus(self):
        menu = Menu(self)
        self.config(menu=menu)
        file_menu = Menu(menu)
        file_menu.add_command( label="Vie tiedostoon",
                               command=lambda: self.export("table.dat") )
        menu.add_cascade( label="Tiedosto", menu=file_menu )
        dep_menu = Menu(menu)
        for id, name in self.source.get_departments():
            dep_menu.add_command( label=name,
                                  command=lambda id_=id: self.source.set_department(id_) )
        menu.add_cascade( label="Laitos", menu=dep_menu )


def main():
    source = CourseModel()
    root = MainWindow(source)
    root.mainloop()


if __name__ == "__main__":
    main()
